package com.ll.sender.impl;

import com.ll.exception.UserException;
import com.ll.exception.UserExceptionConstants;
import com.ll.sender.SendEmailFactory;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * exchange发送邮件
 * 
 * @author dwliu
 *
 * @date 2016年4月19日
 */
@Service
public class ExchangeSend implements SendEmailFactory {

	private static Logger LOGGER = LoggerFactory.getLogger(ExchangeSend.class);
			
	
	/**
	 * exchange发送邮件
	 * 
	 * @param address
	 *            服务器地址
	 * @param port
	 * 			  服务器端口           
	 * @param username
	 *            发件人邮箱
	 * @param password
	 *            发件人密码
	 * @param recipient
	 *            收件人邮箱
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 */
	@Override
	public void send(String address,Integer port, String username, String password, String recipient, String subject,
			String content)  {
		try {
			ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
			ExchangeCredentials credentials = new WebCredentials(username, password);
			service.setCredentials(credentials);
			service.setUrl(new URI(address));
			EmailMessage msg = new EmailMessage(service);
			msg.setSubject(subject);
			msg.setBody(MessageBody.getMessageBodyFromText(content.toString()));
			msg.getToRecipients().add(recipient);
			msg.send();
		} catch (URISyntaxException e) {
			LOGGER.error("smtpAddress地址错误",e);
			throw new UserException(UserExceptionConstants.SMTPADDRESS, e);
		} catch (ServiceLocalException e) {
			LOGGER.error("收件人地址错误",e);
			throw new UserException(UserExceptionConstants.ADDRESSEXCEPTION, e);
		} catch (Exception e) {
			LOGGER.error("发送邮件失败",e);
			throw new UserException(UserExceptionConstants.SENDMESSAGINGEXCEPTION, e);
		}
	}

}
